package com.atguigu.xuexiplus.controller;

import com.atguigu.xuexiplus.dto.LoginUserDTO;
import com.atguigu.xuexiplus.dto.UserDTO;
import com.atguigu.xuexiplus.dto.UpdateProfileDTO;
import com.atguigu.xuexiplus.result.Result;
import com.atguigu.xuexiplus.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * 图书控制器
 */
@RestController
@RequestMapping("/api/user")
@CrossOrigin(origins = "*")
public class UserController {
    @Autowired
    private UserService userService;
    /**
     * 登录
     */
    @PostMapping("/login")
    public Result<Object> login(@RequestBody LoginUserDTO userDTO) {
        try {
            System.out.println("收到登录请求: " + userDTO.getUsername());
            // 1. 调用 service 验证用户名密码
            UserDTO user = userService.login(userDTO.getUsername(), userDTO.getPassword());
            if (user == null) {
                System.out.println("用户名或密码错误: " + userDTO.getUsername());
                return Result.error("用户名或密码错误");
            }
            //4，用户改为上线
            userService.updateStatus(user.getUsername(),1);
            System.out.println("登录成功: " + userDTO.getUsername());
            
            // 返回用户信息
            return Result.success(user);
        } catch (Exception e) {
            System.err.println("登录异常: " + e.getMessage());
            e.printStackTrace();
            return Result.error("登录失败: " + e.getMessage());
        }
    }
    /**
     * 登出
     */
    @PostMapping("/logout")
    public Result logout(@RequestBody LoginUserDTO userDTO) {
        // 1. 调用 service 验证用户名密码（你需要在 UserService 中实现 validateUser）
        UserDTO user = userService.login(userDTO.getUsername(), userDTO.getPassword());
        if (user == null) {
            throw new RuntimeException("用户名或密码错误");
        }
        //4，用户改为下线
        userService.updateStatus(user.getUsername(),0);
        return Result.success();
    }

    /**
     * 获取用户信息（支持通过 userId 或 username 查询）
     */
    @GetMapping("/info")
    public Result<UserDTO> getUserInfo(@RequestParam(value = "userId", required = false) Long userId,
                                       @RequestParam(value = "username", required = false) String username) {
        if (userId == null && (username == null || username.isEmpty())) {
            return Result.error("缺少 userId 或 username 参数");
        }

        UserDTO user;
        if (userId != null) {
            user = userService.findById(userId);
        } else {
            user = userService.findByUsername(username);
        }

        if (user == null) {
            return Result.error("用户不存在");
        }

        // 不返回密码
        user.setPassword(null);
        return Result.success(user);
    }

    /**
     * 更新个人资料（昵称、头像）
     */
    @PutMapping("/profile")
    public Result<UserDTO> updateProfile(@RequestBody UpdateProfileDTO dto) {
        try {
            UserDTO updated = userService.updateProfile(dto);
            if (updated == null) {
                return Result.error("更新失败");
            }
            return Result.success(updated);
        } catch (Exception e) {
            return Result.error("更新失败: " + e.getMessage());
        }
    }

    /**
     * 获取全部用户（在线优先）
     */
    @GetMapping("/list")
    public Result<java.util.List<com.atguigu.xuexiplus.entity.User>> listAll() {
        return Result.success(userService.listAllUsers());
    }

    /**
     * 测试用户接口
     */
    @GetMapping("/test")
    public Result<String> test() {
        System.out.println("用户接口测试被调用");
        return Result.success("用户接口正常工作");
    }

    /**
     * 测试登录响应
     */
    @PostMapping("/test-login")
    public Result<Object> testLogin(@RequestBody LoginUserDTO userDTO) {
        System.out.println("测试登录接口被调用: " + userDTO.getUsername());
        
        // 模拟用户数据
        UserDTO mockUser = new UserDTO();
        mockUser.setId(999L);
        mockUser.setUsername(userDTO.getUsername());
        mockUser.setNickname("测试用户");
        mockUser.setRole(0);
        mockUser.setStatus(1);
        
        return Result.success(mockUser);
    }
    
    /**
     * 测试用户列表响应
     */
    @GetMapping("/test-list")
    public Result<Object> testUserList() {
        System.out.println("测试用户列表接口被调用");
        
        // 模拟用户列表数据
        java.util.List<UserDTO> users = new java.util.ArrayList<>();
        
        UserDTO user1 = new UserDTO();
        user1.setId(1L);
        user1.setUsername("admin");
        user1.setNickname("管理员");
        user1.setStatus(1);
        users.add(user1);
        
        UserDTO user2 = new UserDTO();
        user2.setId(2L);
        user2.setUsername("111");
        user2.setNickname("用户111");
        user2.setStatus(1);
        users.add(user2);
        
        return Result.success(users);
    }
}
